// svg 实现 watermark
export const createWM = (params = {}) => {
  const {
    container = document.body,
    width = '150px',
    height = '150px',
    textAlign = 'center',
    textBaseline = 'middle',
    fontSize = 12,
    fontFamliy = 'Microsoft Yahei',
    textColor = 'rgba(184, 184, 184, 0.2)',
    content = 'Open Components',
    rotate = '-24',
    zIndex = 9000
  } = params
  const args = params
  const canvas = document.createElement('canvas')

  canvas.setAttribute('width', width)
  canvas.setAttribute('height', height)
  const ctx = canvas.getContext('2d')

  ctx.textAlign = textAlign
  ctx.textBaseline = textBaseline
  ctx.font = fontSize + 'px ' + fontFamliy // '12px Microsoft Yahei'
  ctx.fillStyle = textColor
  ctx.rotate(Math.PI / 180 * rotate)
  ctx.fillText(content, parseFloat(width) / 2, parseFloat(height) / 2)

  const base64Url = canvas.toDataURL()
  const __wm = container.querySelector('.__wm')

  const watermarkDiv = __wm || document.createElement('div')
  const styleStr = `
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    z-index:${zIndex};
    pointer-events:none;
    background-repeat:repeat;
    background-image:url('${base64Url}')`

  watermarkDiv.setAttribute('style', styleStr)
  watermarkDiv.classList.add('__wm')

  if (!__wm) {
    container.style.position = 'relative'
    container.insertBefore(watermarkDiv, container.firstChild)
  }
  const MutationObserver = window.MutationObserver || window.WebKitMutationObserver
  let mo = null
  if (MutationObserver) {
    mo = new MutationObserver(() => {
      const __wm = container.querySelector('.__wm')
      // 只在__wm元素变动才重新调用 __canvasWM
      if ((__wm && __wm.getAttribute('style') !== styleStr) || !__wm) {
        // 避免一直触发
        mo.disconnect()
        mo = null
        createWM(args)
      }
    })
    showWM(container, mo)
  }
  return mo
}
export const removeWM = (container, mo) => {
  mo.disconnect()
  const wm = container.querySelector('.__wm')
  if (wm) {
    container.removeChild(wm)
  }
}
export const hideWM = (container, mo) => {
  mo.disconnect()
  const wm = container.querySelector('.__wm')
  if (!wm) return
  wm.style.display = 'none'
}
export const showWM = (container, mo) => {
  const wm = container.querySelector('.__wm')
  if (!wm) return
  if (wm.style.display === 'none') {
    wm.style.display = 'block'
  }
  mo.observe(container, {
    attributes: true,
    subtree: true,
    childList: true
  })
}
